package info.opensoaring.api.igc;

import info.opensoaring.util.igc.LogParser;
import info.opensoaring.util.igc.LogUtil;

import java.io.Serializable;
import java.util.ArrayList;

public class FlightLog implements Serializable {

    private static final long serialVersionUID = 5741750802056404151L;

    private double maxSpeed = 350;

    private String igcData;

    private FlightProperties flightProps;

    private ArrayList<Fix> flightFixes = new ArrayList<Fix>();

    public FlightLog() {
	this(null);
    }

    public FlightLog(String igcData) {
	this.igcData = igcData;
	this.flightProps = new FlightProperties();
    }

    public String getIgcData() {
	return igcData;
    }

    public void setIgcData(String igcData) {
	this.igcData = igcData;
    }

    public FlightProperties getFlightProps() {
	return flightProps;
    }

    public void setFlightProps(FlightProperties flightProps) {
	this.flightProps = flightProps;
    }

    public ArrayList<Fix> getFlightFixes() {
	return flightFixes;
    }

    public void setFlightFixes(ArrayList<Fix> flightFixes) {
	this.flightFixes = flightFixes;
    }

    public double getMaxSpeed() {
	return maxSpeed;
    }

    public void setMaxSpeed(double maxSpeed) {
	this.maxSpeed = maxSpeed;
    }

    public void parse() {
	String[] records = igcData.split("\n|\r|\r\n");
	for (String record : records) {
	    char recordType = record.charAt(0);
	    switch (recordType) {
	    case 'A':
		LogParser.parseRecorderInfo(record, flightProps);
		break;
	    case 'B':
		flightFixes.add(LogParser.parseFix(record, flightProps));
		break;
	    case 'C':
		LogParser.parseFlightDeclaration(record, flightProps);
	    case 'H':
		LogParser.parseHeaderInfo(record, flightProps);
		break;
	    case 'I':
		LogParser.parseFixExtensions(record, flightProps);
		break;
	    }
	}
    }

    public void validate() {
	for (int i = 1; i < flightFixes.size(); i++) {
	    double speed = LogUtil.groundSpeed(flightFixes.get(i - 1), flightFixes.get(i));
	    if (speed > maxSpeed) {
		flightFixes.remove(i);
		++i;
	    }
	}
    }

    public void parseAndValidate() {
	parse();
	validate();
    }

    public String toString() {
	return "{Properties=" + getFlightProps() + ",FlightFixes(size)=" + getFlightFixes().size()
		+ "}";
    }

}
